package com.wang.factory;

import com.wang.util.TransactionManager;

import java.lang.reflect.Proxy;

/**
 * Created by wangq on 2021/7/12.
 */
public class ProxyFactory {
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

//    private ProxyFactory() {
//
//    }
//
//    private static ProxyFactory proxyFactory = new ProxyFactory();
//
//    public static ProxyFactory getInstance() {
//        return proxyFactory;
//    }


    /**
     * 获取需要事务管理的对象的动态代理
     *
     * @param object 需要获取动态代理的对象
     * @return 动态代理
     */
    public Object getTransactionJdkProxy(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), (proxy, method, args) -> {
            Object result;
            try {
                System.out.println("增强逻辑【开启事务】");
                // 开启事务(关闭事务自动提交)
                transactionManager.beginTransaction();

                // 调用代理对象中的方法
                result = method.invoke(object, args);

                System.out.println("增强逻辑【提交事务】");
                // 提交事务
                transactionManager.commit();

            } catch (Exception exception) {
                exception.printStackTrace();
                System.out.println("增强逻辑【回滚事务】");
                // 回滚事务
                transactionManager.rollback();
                // 抛出异常
                throw exception;
            }
            return result;
        });
    }
}
